﻿/*******************************************************************   
 * 创建日期：2021.07.09 13:41:41  
 * 创 建 者：Administrator 
 * 功能描述：World  
 *******************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cars
{
    internal class World
    {
        int s_Speed;

        /// <summary>
        /// 游戏世界
        /// </summary>
        /// <param name="width">窗口宽度</param>
        /// <param name="height">窗口高度</param>
        /// <param name="speed">游戏速度(刷新时间:毫秒)</param>
        public World(int width,int height,int speed)
        {
            Console.BufferWidth = Console.WindowWidth = width;
            Console.BufferHeight = Console.WindowHeight = height;
            s_Speed = speed;
        }

        public void Run()
        {
            Thread musicThread = new Thread(BGM.PlayBgm);
            musicThread.Start();

            Console.CursorVisible = false;
            //创建玩家对象
            Position ori = new Position(0, Console.BufferHeight - 1);
            PlayerActor playerActor = new PlayerActor('$', ConsoleColor.Green, 1000, ori);            
            PlayerController.Instance.ControllerActor = playerActor;

            List<Actor> allActors = new List<Actor>();

            Random random = new Random();
             

            while (true)
            {
                Console.Clear();
                PlayerController.Instance.Run();

                for (int i = 0; i < 5; i++)
                {
                    var obstaclePos = new Position(random.Next(0, Console.BufferWidth-1), 0);

                    var obstacleActor = new ObstacleActor(obstaclePos, '#', ConsoleColor.Red);

                    allActors.Add(obstacleActor);
                }

                foreach (var actor in allActors.ToList())
                {
                    actor.Draw();
                    //这里比较特殊，坐标向下是Y轴增加
                    actor.Move(Position.up);

                    if (actor.Dead())
                    {
                        allActors.Remove(actor);
                    }
                }

                Thread.Sleep(s_Speed);

            }
        }
    }
}
